package cn.stacey.blog.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.stacey.blog.mapper.CategoryMapper;
import cn.stacey.blog.service.CategoryService;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 传入一个原始对象
 * 返回一个增强过的service对象
 * 增强：在service方法调用之前加入处理：打开sesion
 * 		在service方法调用之后添加处理：关闭session,提交事务
 * @author 袁
 *
 */

public class ServiceProxyUtils
 {
	public static Object createProxy(Object service) {
		Enhancer enhancer=new Enhancer();
		enhancer.setSuperclass(service.getClass());
		enhancer.setCallback(new MethodInterceptor() {//方法拦截器,原始对象上调用任何方法都会被代理对象拦截到

			@Override
			public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy methodProxy) throws Throwable {
				//打开session
				SqlSessionFactory factory = SessionFactoryUtils.getFactory();
				SqlSession session = factory.openSession();
				//使用反射，给原始service对象里面的mapper进行初始化赋值
				Field field = service.getClass().getDeclaredField("mapper");
				//动态的取到Mapper对象的类型,而不是session.getMapper(CategoryMapper.class)
				Class<?> type=field.getType();
				field.setAccessible(true);
				field.set(service, session.getMapper(type));
				//mapper = session.getMapper(CategoryMapper.class);
				//执行原有的方法
				Object result = methodProxy.invoke(service, arg2);
				
				//提交事务
				session.commit();
				session.close();
				return result;
			}
			
		});
	
		return enhancer.create();	
		
	}
}
